package cn.codingjc.peekaboo.application.config.repeat;

import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @auth: coding_jc
 * @date: 2023/5/12 10:34
 * @desc: 可重复读过滤器
 */

@WebFilter(filterName = "RepeatFilter", urlPatterns = "/*")
public class RepeatFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        ServletRequest requestWrapper = null;
        if (request instanceof HttpServletRequest && StringUtils.startsWithIgnoreCase(request.getContentType(), MediaType.APPLICATION_JSON_VALUE)) {
            requestWrapper = new RepeatRequestWrapper((HttpServletRequest) request, (HttpServletResponse) response);
        }
        // 非json请求
        if (requestWrapper == null) {
            chain.doFilter(request, response);
        } else {
           chain.doFilter(requestWrapper, response);
        }

    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
